using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using ZXing;
using ZXing.Common;

namespace SoftManager
{
    public class CodeHelper
    {
        private string _charset = "UTF-8";//默认的貌似中文不能识别，解码后会是？号
        public string CHARSET
        {
            get
            {
                return _charset;
            }
            set
            {
                _charset = value;
            }
        }
        public int SaveTo(Bitmap bitmap, string filepath, string filename)
        {
            try
            {
                bitmap.Save(filepath + filename);
                return 0;
            }
            catch (Exception)
            {
                return -1;
            }
        }

        public Bitmap encode(string content, int width, int height, BarcodeFormat barcodeFormat, IDictionary<EncodeHintType, object> hints)
        {
            BitMatrix byteMatrix = new MultiFormatWriter().encode(content, barcodeFormat, width, height, hints);
            Bitmap bitmap = toBitmap(byteMatrix);

            //Bitmap logo = new Bitmap(@"d:\logoImg.png");
            //bitmap = addLogo(byteMatrix,bitmap,logo);
            return bitmap;
        }

        public Bitmap encode(string content, int width, int height, BarcodeFormat barcodeFormat)
        {
            BitMatrix byteMatrix = new MultiFormatWriter().encode(content, barcodeFormat, width, height);
            Bitmap bitmap = toBitmap(byteMatrix);
            return bitmap;
        }

        public static Bitmap toBitmap(BitMatrix matrix)
        {
            int width = matrix.Width;
            int height = matrix.Height;
            Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bmap.SetPixel(x, y, matrix[x, y] ? ColorTranslator.FromHtml("0xFF000000") : ColorTranslator.FromHtml("0xFFFFFFFF"));
                }
            }
            return bmap;
        }

        public int encodeAndSave(string content, string path, int width, int height, BarcodeFormat barcodeFormat)
        {
            return SaveTo(encode(content, width, height, barcodeFormat), path, "");
        }

        public int decode(string bmppath, IDictionary<DecodeHintType, object> hints, out Result result)
        {
            Bitmap bmap = new Bitmap(bmppath);
            BitmapLuminanceSource source = new BitmapLuminanceSource(bmap);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            result = new MultiFormatReader().decode(bitmap, hints);

            return 0;
        }

        private Bitmap addLogo(BitMatrix matrix, Bitmap src, Bitmap logo)
        {
            int[] rectangle = matrix.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
            int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
            int middleL = (src.Width - middleW) / 2;
            int middleT = (src.Height - middleH) / 2;

            using (Graphics g = Graphics.FromImage(src))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(src, 0, 0);
            }
            //将二维码插入图片
            Graphics myGraphic = Graphics.FromImage(src);

            myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);

            myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

            return src;
        }

        /// <summary>
        /// HTTP GET请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="headerDic"></param>
        /// <param name="Method"></param>
        /// <returns></returns>
        public static string HttpGetJson(string Url, Dictionary<string, string> headerDic = null, string Method = "GET")
        {
            string jsons;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);    //创建一个请求示例 
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        request.Headers[item.Key] = item.Value; //添加头
                    }
                }
                //request.Headers["键"] = "值"; //添加头
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();  //获取响应，即发送请求

                Stream responseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                jsons = streamReader.ReadToEnd();
            }
            catch
            {
                return "";
            }
            return jsons;
        }

        /// <summary>
        /// HTTP POST请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="paramData"></param>
        /// <param name="headerDic"></param>
        /// <param name="Method"></param>
        /// <returns></returns>
        public static string HttpPostJson(string Url, string paramData, Dictionary<string, string> headerDic = null, string Method = "POST")
        {
            string jsons;
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(Url);
                wbRequest.KeepAlive = false;
                wbRequest.Method = Method;
                wbRequest.ContentType = "application/json";
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        jsons = sread.ReadToEnd();
                    }
                }
            }
            catch
            {
                //MessageBox.Show(ex.Message, "服务连接");
                return "";
            }
            return jsons;
        }
    }
}